#include "choosefrienddialog.h"
#include"model/datacenter.h"
#include<QMessageBox>
#include<QTimer>

ChooseFriendDialog::ChooseFriendDialog(const QString &userId, QWidget *parent)
    :QDialog(parent), userId(userId)
{
    // 设置关闭后⾃动销毁
    this->setAttribute(Qt::WA_DeleteOnClose);

    // 1. 设置基本属性
    this->setWindowTitle("选择好友");
    this->setWindowIcon(QIcon(":/images/logo.png"));
    // 隐藏标题栏
    // this->setWindowFlags(Qt::FramelessWindowHint);
    this->setFixedSize(755, 550);
    this->setStyleSheet("QDialog {background-color: rgb(255, 255, 255);}");

    // 2. 创建核⼼布局(左右结构).
    QHBoxLayout* layout = new QHBoxLayout();
    layout->setContentsMargins(0, 0, 0, 0);
    layout->setSpacing(0);
    this->setLayout(layout);

    // 3. 创建左侧筛选好友列表
    initLeft(layout);
    // 4. 创建右侧已选中好友列表
    initRight(layout);

#if LOAD_DATA_FROM_NETWORK
    model::DataCenter* dataCenter = model::DataCenter::getInstance();
    QList<model::UserInfo>* friendList = dataCenter->getFriendList();
    if (friendList == nullptr) {
        return;
    }
    for (auto it = friendList->begin(); it != friendList->end(); ++it) {
        if (it->userId == this->userId) {
            // 对于当前会话的好友, 直接就默认选中
            this->addFriend(it->userId, it->avatar, it->nickname, true);
            this->addSelectedFriend(it->userId, it->avatar, it->nickname);
        } else {
            this->addFriend(it->userId, it->avatar, it->nickname, false);
        }
    }
#endif
}

void ChooseFriendDialog::addFriend(const QString &userId, const QIcon avatar, const QString &name, bool checked)
{
    ChooseFriendItem* item = new ChooseFriendItem(this, userId, avatar, name,checked);
    QVBoxLayout* layout = dynamic_cast<QVBoxLayout*>(totalContainer->layout());
    layout->addWidget(item);
}

void ChooseFriendDialog::addSelectedFriend(const QString &userId, const QIcon avatar, const QString &name)
{
    ChooseFriendItem* item = new ChooseFriendItem(this, userId, avatar, name,true);
    QVBoxLayout* layout = dynamic_cast<QVBoxLayout*>(selectedContainer->layout());
    layout->addWidget(item);
}



void ChooseFriendDialog::deleteSelectedFriend(const QString &userId)
{
    // 1. 删除已选中列表中的元素
    QVBoxLayout* layoutSelected = dynamic_cast<QVBoxLayout*>(selectedContainer->layout());
    // 遍历 + 删除, 需要从后往前遍历.
    for (int i = layoutSelected->count() - 1; i >= 0; --i) {
        auto* item = layoutSelected->itemAt(i);
        if (item == nullptr || item->widget() == nullptr) {
            continue;
        }
        ChooseFriendItem* chooseFriendItem = dynamic_cast<ChooseFriendItem*>(item->widget());
        if (chooseFriendItem->userId != userId) {
            continue;
        }
        // 从布局管理器中移除元素
        layoutSelected->removeItem(item);
        // 不要忘记释放内存
        chooseFriendItem->deleteLater();
    }

    // 2. 确认好友列表中的 checkbox 的值为未选中状态.
    // 这个逻辑⽤来处理只在右侧选中列表取消 checkBox 后, 在左侧列表不能⾃动取消的bug
        QVBoxLayout* layoutTotal = dynamic_cast<QVBoxLayout*>(totalContainer->layout());
    for (int i = 0; i < layoutTotal->count(); ++i) {
        auto* item = layoutTotal->itemAt(i);
        if (item == nullptr || item->widget() == nullptr) {
            continue;
        }
        ChooseFriendItem* chooseFriendItem = dynamic_cast<ChooseFriendItem*>(item->widget());
        if (chooseFriendItem->userId != userId) {
            continue;
        }
        // 如果该选项的 checkBox 值修改为 false
        chooseFriendItem->checkBox->setChecked(false);
    }
}

void ChooseFriendDialog::initLeft(QHBoxLayout *layout)
{
    // 1. 创建滚动区
    QScrollArea* scrollArea = new QScrollArea();
    scrollArea->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    // ⼀定要添加这个设置, 否则⽆法正确显⽰.
    scrollArea->setWidgetResizable(true);
    // 隐藏⽔平滚动条. 把垂直滚动条设置的细⼀些.

    scrollArea->verticalScrollBar()->setStyleSheet("QScrollBar:vertical {width: 2px; background-color: rgb(255, 255, 255); }\
                                    QScrollBar::handle:vertical {background-color: rgb(205, 205, 205);}");
    scrollArea->horizontalScrollBar()->setStyleSheet("QScrollBar:horizontal {height: 0px;}");

    scrollArea->setStyleSheet("QScrollArea { border: none; }");
    layout->addWidget(scrollArea, 1);
    totalContainer = new QWidget();
    totalContainer->setObjectName("totalContainer");
    totalContainer->setStyleSheet("#totalContainer {background-color: rgb(255,255, 255);}");
    scrollArea->setWidget(totalContainer);

    // 2. 创建⼦布局管理器
    QVBoxLayout* vlayout = new QVBoxLayout();
    vlayout->setContentsMargins(0, 0, 0, 0);
    vlayout->setSpacing(0);
    vlayout->setAlignment(Qt::AlignTop); // 设置靠上⽅对⻬
    totalContainer->setLayout(vlayout);

// 3. 添加所有待选择的好友
#if TEST_UI
    for (int i = 0; i < 30; i++) {
        this->addFriend(QString::number(i), QIcon(":/images/default_avatar.jpg"), "张三",false);
    }
#endif
}

void ChooseFriendDialog::initRight(QHBoxLayout *layout)
{
    // 1. 创建⽹格布局
    QGridLayout* gridLayout = new QGridLayout();
    gridLayout->setContentsMargins(20, 20, 20, 20);
    gridLayout->setSpacing(10);

    // 2. 创建顶部提⽰语
    QLabel* tipLabel = new QLabel();
    tipLabel->setText("选择联系⼈");
    tipLabel->setFixedHeight(30);
    tipLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    tipLabel->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
    tipLabel->setStyleSheet("QLabel { font-size:16px; font-weight: 700; }");

    // 3. 创建中间滚动区
    QScrollArea* scrollArea = new QScrollArea();
    scrollArea->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    // ⼀定要添加这个设置, 否则⽆法正确显⽰.
    scrollArea->setWidgetResizable(true);
    // 隐藏⽔平滚动条. 把垂直滚动条设置的细⼀些.
    scrollArea->verticalScrollBar()->setStyleSheet("QScrollBar:vertical {width: 2px; background-color: rgb(255, 255, 255); }\
                                                    QScrollBar::handle:vertical {background-color: rgb(205, 205, 205);}");
    scrollArea->horizontalScrollBar()->setStyleSheet("QScrollBar:horizontal {height: 0px;}");
    scrollArea->setStyleSheet("QScrollArea { border: none; }");

    selectedContainer = new QWidget();
    selectedContainer->setObjectName("selectedContainer");
    selectedContainer->setStyleSheet("#selectedContainer {background-color:rgb(255, 255, 255);}");
    scrollArea->setWidget(selectedContainer);

    QVBoxLayout* vlayout = new QVBoxLayout();
    vlayout->setContentsMargins(0, 0, 0, 0);
    vlayout->setSpacing(0);
    vlayout->setAlignment(Qt::AlignTop); // 设置靠上⽅对⻬
    selectedContainer->setLayout(vlayout);

    // 4. 创建底部按钮
    QString style = "QPushButton { color: rgb(7, 193, 96); background-color:rgb(243, 243, 243); border: none; border-radius: 5px;}";
    style += "QPushButton:hover {background-color: rgb(219, 219, 219);}QPushButton:pressed {background-color: rgb(206, 206, 206);}";

    QPushButton* okBtn = new QPushButton();
    okBtn->setText("完成");
    okBtn->setFixedHeight(40);
    okBtn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    okBtn->setStyleSheet(style);

    QPushButton* cancelBtn = new QPushButton();
    cancelBtn->setText("取消");
    cancelBtn->setStyleSheet(style);
    cancelBtn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    cancelBtn->setFixedHeight(40);
    connect(cancelBtn, &QPushButton::clicked, this, [=]() {
        // 关闭对话框, 并返回 "QDialog::Rejected"
        this->reject();
    });

    // 5. 放到布局中. 整体分成 9 个列. tipLabel 和 scrollArea 占满 9 列. 下⾯的按钮各⾃占 3 列. 剩下 3 列是左中右的空隙
    gridLayout->addWidget(tipLabel, 0, 0, 1, 9);
    gridLayout->addWidget(scrollArea, 1, 0, 1, 9);
    gridLayout->addWidget(okBtn, 2, 1, 1, 3);
    gridLayout->addWidget(cancelBtn, 2, 5, 1, 3);
    layout->addLayout(gridLayout, 1);

//6. 创建测试数据
#if TEST_UI
    for (int i = 0; i < 30; i++) {
        this->addSelectedFriend(QString::number(i),QIcon(":/images/default_avatar.jpg"), "张三");
    }
#endif

    //确认选择
    connect(okBtn, &QPushButton::clicked, this, &ChooseFriendDialog::clickOkBtn);
}

void ChooseFriendDialog::clickOkBtn()
{
    QList<QString> userIdList = getNumberList();
    if(userIdList.size() <= 2){
        LOG() << "当前会话成员数目不满足条件";
        QMessageBox* messageBox = new QMessageBox(this);
        messageBox->setWindowTitle("提示");
        messageBox->setText("当前会话成员数目不满足条件");
        messageBox->setIcon(QMessageBox::Information);
        messageBox->setStandardButtons(QMessageBox::NoButton); // 不显示按钮

        // 显示弹窗
        messageBox->show();

        // 设置2秒后自动关闭
        QTimer::singleShot(2000, messageBox, [messageBox]() {
            messageBox->close();
            messageBox->deleteLater(); // 释放内存
        });

        return;
    }

    // 2. 发送请求
    model::DataCenter* dataCenter = model::DataCenter::getInstance();
    dataCenter->createChatSessionAsync(userIdList);
    // 3. 关闭窗⼝, 返回 "QDialog::Accepted"
    this->accept();
}

QList<QString> ChooseFriendDialog::getNumberList()
{
    QList<QString> result;
    // 1. 先把⾃⼰加进去
    model::DataCenter* dataCenter = model::DataCenter::getInstance();
    model::UserInfo* userInfo = dataCenter->getMyselfInfo();
    if (userInfo == nullptr) {
        qCritical() << TAG << "获取个⼈信息失败!";
        return result;
    }
    result.push_back(userInfo->userId);

    QVBoxLayout* layout = dynamic_cast<QVBoxLayout*>(selectedContainer->layout());
    for(int i = 0; i < layout->count(); ++i){
        auto* item = layout->itemAt(i);
        if(item == nullptr || item->widget() == nullptr){
            continue;
        }

        ChooseFriendItem* friendItem = dynamic_cast<ChooseFriendItem*>(item->widget());
        result.push_back(friendItem->userId);
    }

    return result;
}

ChooseFriendItem::ChooseFriendItem(ChooseFriendDialog *owner, const QString &userId, const QIcon &avatar, const QString &name, bool checked)
    : owner(owner), userId(userId), avatar(avatar), name(name), isHover(false)
{
    this->setFixedHeight(50);
    this->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);

    QHBoxLayout* layout = new QHBoxLayout();
    layout->setContentsMargins(10, 5, 10, 5);
    layout->setSpacing(10);
    this->setLayout(layout);

    // 创建头像
    QPushButton* avatarBtn = new QPushButton();
    avatarBtn->setFixedSize(40, 40);
    avatarBtn->setIconSize(QSize(40, 40));
    avatarBtn->setIcon(avatar);
    // 创建名字
    QLabel* nameLabel = new QLabel();
    nameLabel->setText(name);
    nameLabel->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);

    // 创建复选框
    checkBox = new QCheckBox();
    checkBox->setFixedSize(25, 25);
    checkBox->setChecked(checked);
    checkBox->setStyleSheet("QCheckBox::indicator { width: 20px; height:20px;image: url(:/images/unchecked.png); }\
                             QCheckBox::indicator:checked { image:url(:/images/checked.png); }");
    connect(checkBox, &QCheckBox::toggled, this, &ChooseFriendItem::toggleCheckBox);

    // 添加到布局管理器中
    layout->addWidget(checkBox);
    layout->addWidget(avatarBtn);
    layout->addWidget(nameLabel);
}

void ChooseFriendItem::enterEvent(QEnterEvent *event)
{
    (void) event;
    isHover = true;
    repaint();
}

void ChooseFriendItem::leaveEvent(QEvent *event)
{
    (void) event;
    isHover = false;
    repaint();
}

void ChooseFriendItem::paintEvent(QPaintEvent *event)
{
    (void) event;
    QPainter painter(this);
    if (isHover) {
        painter.fillRect(rect(), QColor(231, 231, 231));
    } else {
        painter.fillRect(rect(), QColor(255, 255, 255));
    }
}

void ChooseFriendItem::toggleCheckBox(bool checked)
{
    if (checked) {
        // 添加到右侧区域中
        owner->addSelectedFriend(userId, avatar, name);
    } else {
        // 从右侧区域中删除
        owner->deleteSelectedFriend(userId);
    }
}
